//亮点：像nuxt一样可以自动进行配置

//难点：扁平路由转树形

//require.context("路径","是否递归引入","正则")   一次导入多个模块

//创建路由配置
let files = require.context("@/pages", true, /\.vue$/);

//每个路由文件的路径
// [
//   "./home/Attendance/index.vue",
//   "./home/Mine/index.vue",
//   "./home/index.vue",
//   "./layout/Header.vue",
//   "./layout/container.vue",
//   "./login/commonLogin.vue",
//   "./login/index.vue",
//   "./login/msgLogin.vue",
//   "./login/qrLogin.vue",
// ];
// console.log(files.keys());

let repeatRoutes = files.keys().map((path) => {
  //通过正则去掉index.vue 或者.vue的后缀
  let reg = /(\/index\.vue|\.vue)$/;
  //获取路径对应的每个.vue组件
  let currentComponet = files(path).default;
  // console.log(currentComponet);
  //解构组件 export default 导出的对象中添加的属性
  let { meta, name, redirect } = currentComponet;

  path = path.substring(1).replace(reg, "");
  // console.log(path);

  return {
    path: path ? path : "/pages",
    //重定向 name属性 meta元信息
    meta: meta ?? {},
    name: name ?? path.substring("1").split("/").join("-").toLowerCase(),
    redirect: redirect ?? null,
    component: () => import("@/pages" + path),
  };
});
// [
//   { path: "/home/Attendance", component: ƒ },
//   { path: "/home/Mine", component: ƒ },
//   { path: "/home", component: ƒ },
//   { path: "/layout/Header", component: ƒ },
//   { path: "/layout/container", component: ƒ },
//   { path: "/login/commonLogin", component: ƒ },
//   { path: "/login", component: ƒ },
//   { path: "/login/msgLogin", component: ƒ },
//   { path: "/login/qrLogin", component: ƒ },
// ];
// console.log(repeatRoutes);

function converTree(repeatRoutes) {
  let treeRoutes = [];
  //给数据添加id 和 pid
  repeatRoutes.forEach((route) => {
    //将路径去掉第一个/,转换成数组
    let routerPathArr = route.path.substring(1).split("/");
    // console.log(routerPathArr);
    // length为1的都是根节点

    //添加id 和 pid
    //添加id
    route.id = routerPathArr.join("-");
    // console.log(route.id, "id");
    if (routerPathArr.length > 1) {
      let pathArr = [...routerPathArr];
      pathArr.pop();
      // console.log(pathArr);
      let pid = pathArr.join("-");
      route.pid = pid; //给自己添加pid
      // console.log(route.pid, "pid");
    }
  });
  //转换成树形数据
  repeatRoutes.forEach((route) => {
    //将所有路径都变成小写  为了后面和菜单高亮效果绑定
    route.path = route.path.toLowerCase();
    //404
    if (route.path === "/page404") {
      route.path = "*";
    }
    //找父节点
    let parent = repeatRoutes.find((v) => route.pid === v.id);
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      //子路由路径
      route.path = route.path.substring(1).split("/").pop();
      // console.log(route.path);

      parent.children.push(route);
    } else {
      treeRoutes.push(route);
    }
  });
  return treeRoutes;
}
let res = converTree(repeatRoutes);
console.log(res, 12345);

export default [...res];
